/**
* @file				arduino.c
* @author  		Supachai Vorapojpisut
* @version 		0.5
* @date    		November 11, 2013
* @brief   		Arduino compatibility module - add analogWrite()
*/

/* Includes ------------------------------------------------------------------*/
#include "arduino.h"
#include <stm32f0xx.h>
#include <stdio.h>

/* Private define ------------------------------------------------------------*/
#define SERIAL_BUFFER_SIZE 	256

#define PWM_FREQ			1000

/* Private typedef -----------------------------------------------------------*/
typedef struct {
	uint8_t buffer[SERIAL_BUFFER_SIZE];
	volatile unsigned int head;
	volatile unsigned int tail;
} ring_buffer;

/* Private macro -------------------------------------------------------------*/
#define digitalPinToPort(P) 	( DIGITAL_PIN_TO_PORT[P] )
#define digitalPinToBitMask(P) 	( DIGITAL_PIN_TO_BIT_MASK[P] )
#define analogPinToBitMask(P) 	( ANALOG_PIN_TO_BIT_MASK[P] )
#define analogPinToChannel(P)	( ANALOG_PIN_TO_CHANNEL[P] )
#define digitalPinToTimer(P)	( DIGITAL_PIN_TO_TIMER[P] )
#define digitalPinToChannel(P)	( DIGITAL_PIN_TO_CHANNEL[P] )

/* Private function prototypes -----------------------------------------------*/
void begin_fcn(uint32_t);
uint16_t available_fcn(void);
void flush_fcn(void);
char read_fcn(void);
char peek_fcn(void);
void write_fcn(unsigned char);
void print_fcn(char*);
void println_fcn(char*);  

/* Private variables ---------------------------------------------------------*/
GPIO_TypeDef *DIGITAL_PIN_TO_PORT[14]= {GPIOA, GPIOA, GPIOB, GPIOB, GPIOA, GPIOB, GPIOB, GPIOA, GPIOA, GPIOA, GPIOA, GPIOB, GPIOB, GPIOB};
uint16_t DIGITAL_PIN_TO_BIT_MASK[14] = {GPIO_Pin_3, GPIO_Pin_2, GPIO_Pin_12, GPIO_Pin_11, GPIO_Pin_7, GPIO_Pin_9, GPIO_Pin_8, GPIO_Pin_6, GPIO_Pin_5, GPIO_Pin_4, GPIO_Pin_11, GPIO_Pin_5, GPIO_Pin_4, GPIO_Pin_3};
uint16_t ANALOG_PIN_TO_BIT_MASK[6] = {GPIO_Pin_0, GPIO_Pin_1, GPIO_Pin_2, GPIO_Pin_3, GPIO_Pin_4, GPIO_Pin_5};
uint32_t ANALOG_PIN_TO_CHANNEL[6] = {ADC_Channel_10, ADC_Channel_11, ADC_Channel_12, ADC_Channel_13, ADC_Channel_14, ADC_Channel_15};

static uint32_t msTick = 0;

static ring_buffer _rx_buffer;
static ring_buffer _tx_buffer;
static int transmitting = 0;
int pwmInputVal;
int pwmInputValMILI;

/* Private functions ---------------------------------------------------------*/

// SysTick handler to implement timebase features.
//void SysTick_Handler()
//{
//	msTick++;
//}


// Implementation of Serial.begin()
void begin_fcn(uint32_t baudRate) {
	USART_InitTypeDef usart_init_struct;
	GPIO_InitTypeDef gpio_init_struct;
	NVIC_InitTypeDef nvic_init_struct;
	
	// Enable and configure USART2 components
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
	usart_init_struct.USART_BaudRate = baudRate;
	usart_init_struct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	usart_init_struct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
	usart_init_struct.USART_Parity = USART_Parity_No;
	usart_init_struct.USART_StopBits = USART_StopBits_1;
	usart_init_struct.USART_WordLength = USART_WordLength_8b;
	USART_Init(USART2, &usart_init_struct);
	
	// Enable AF features for pins PA3 and PA2
	GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_1);
	GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_1);

	// Configure Rx pin (D0) with AF
	gpio_init_struct.GPIO_Mode = GPIO_Mode_AF;
	gpio_init_struct.GPIO_PuPd = GPIO_PuPd_UP;
	gpio_init_struct.GPIO_Pin = digitalPinToBitMask(0);
	GPIO_Init(digitalPinToPort(0), &gpio_init_struct);
	
	// Configure Tx pin (D1) with AF
	gpio_init_struct.GPIO_OType = GPIO_OType_PP;
	gpio_init_struct.GPIO_Speed = GPIO_Speed_Level_3;
	gpio_init_struct.GPIO_PuPd = GPIO_PuPd_NOPULL;
	gpio_init_struct.GPIO_Pin = digitalPinToBitMask(1);
	GPIO_Init(digitalPinToPort(1), &gpio_init_struct);
	
	// Configure NVIC with USART2 as interrupt source
	nvic_init_struct.NVIC_IRQChannel = USART2_IRQn;
	nvic_init_struct.NVIC_IRQChannelCmd = ENABLE;
	nvic_init_struct.NVIC_IRQChannelPriority = 0;
	NVIC_Init(& nvic_init_struct);
	
	// Enable USART2 with RXNE condition
	USART_Cmd(USART2, ENABLE);
	USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
	USART_ITConfig(USART2, USART_IT_TXE, DISABLE);
	
	_rx_buffer.head = 0;
	_rx_buffer.tail = 0;
	_tx_buffer.head = 0;
	_tx_buffer.tail = 0;
}


// Implementation of Serial.available()
uint16_t available_fcn(void){
	return (uint16_t)(SERIAL_BUFFER_SIZE + _rx_buffer.head - _rx_buffer.tail) % SERIAL_BUFFER_SIZE;
}


// Implementation of Serial.flush()
void flush_fcn(void){
	while (transmitting && !USART_GetFlagStatus(USART2, USART_FLAG_TC));
	transmitting = 0;
}


// Implementation of Serial.read()
char read_fcn(void){
	if (_rx_buffer.head == _rx_buffer.tail) {
		return -1;
	} else {
		unsigned char c = _rx_buffer.buffer[_rx_buffer.tail];
		_rx_buffer.tail = (_rx_buffer.tail + 1) % SERIAL_BUFFER_SIZE;
		return c;
	}
}


// Implementation of Serial.peek()
char peek_fcn(void){
	if (_rx_buffer.head == _rx_buffer.tail) {
		return -1;
	} else {
		return _rx_buffer.buffer[_rx_buffer.tail];
	}
}


// Implementation of Serial.write()
void write_fcn(uint8_t byte){
	int i = (_tx_buffer.head + 1) % SERIAL_BUFFER_SIZE;

	// Send immediately if Tx buffer is empty and not transmitting
	if ( (_tx_buffer.head == _tx_buffer.tail) && !transmitting ) {
		USART_SendData(USART2, byte);
		USART_ITConfig(USART2, USART_IT_TXE, ENABLE);
		transmitting = 1;
		return;
	}
	
	// Wait for empty space in buffer
	while (i == _tx_buffer.tail);
	
	_tx_buffer.buffer[_tx_buffer.head] = byte;
	_tx_buffer.head = i;
	
	USART_ITConfig(USART2, USART_IT_TXE, DISABLE);
	transmitting = 1;
	USART_ITConfig(USART2, USART_IT_TXE, ENABLE);
}


// Implementation of Serial.print()
void print_fcn(char *string){
	while (*string != 0) {
		write_fcn(*string);
		string++;
	}		
}


// Implementation of Serial.println()
void println_fcn(char *string){
	print_fcn(string);
	write_fcn('\r');
	write_fcn('\n');
}


// Interrupt handler
void USART2_IRQHandler()
{
	if (USART_GetITStatus(USART2, USART_IT_TXE) == SET) {
		if (_tx_buffer.head != _tx_buffer.tail) {
			USART_SendData(USART2, _tx_buffer.buffer[_tx_buffer.tail]);
			_tx_buffer.tail = (_tx_buffer.tail + 1) % SERIAL_BUFFER_SIZE;
		} else {
			USART_ClearITPendingBit(USART2, USART_IT_TXE);
			USART_ITConfig(USART2, USART_IT_TXE, DISABLE);
			transmitting = 0;
		}
	} 
	if (USART_GetITStatus(USART2, USART_IT_RXNE) == SET) {
		_rx_buffer.buffer[_rx_buffer.head] = USART_ReceiveData(USART2);
		_rx_buffer.head = (_rx_buffer.head + 1) % SERIAL_BUFFER_SIZE;
	}
}


/* Global functions ----------------------------------------------------------*/
Serial_TypeDef Serial = {
	0,
	begin_fcn,
	available_fcn,
	flush_fcn,
	read_fcn,
	peek_fcn,
	write_fcn,
	print_fcn,
	println_fcn,
};


/**
* @brief	Initialization code to configure STM32F0 Discovery board for Arduino compatibility
* @param	None
* @retval	None
*/
void platform_config()
{
	GPIO_InitTypeDef gpio_init_struct;
	ADC_InitTypeDef adc_init_struct;
	int i;
		
	RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA | RCC_AHBPeriph_GPIOB | RCC_AHBPeriph_GPIOC, ENABLE);
	// Configure analog pins
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
	
	adc_init_struct.ADC_ContinuousConvMode = DISABLE;
	adc_init_struct.ADC_ScanDirection = ADC_ScanDirection_Upward;
	adc_init_struct.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T1_CC4;
	adc_init_struct.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
	adc_init_struct.ADC_Resolution = ADC_Resolution_12b;
	adc_init_struct.ADC_DataAlign = ADC_DataAlign_Right;
	ADC_Init(ADC1, &adc_init_struct);
	
	for (i = 0; i < 5; i++) {
		gpio_init_struct.GPIO_Pin = analogPinToBitMask(i);
		gpio_init_struct.GPIO_Mode = GPIO_Mode_AN;
		gpio_init_struct.GPIO_PuPd = GPIO_PuPd_NOPULL;
		GPIO_Init(GPIOC, &gpio_init_struct);
	}
	
	ADC_GetCalibrationFactor(ADC1);
	ADC_Cmd(ADC1, ENABLE);
	while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_ADEN)); 
	
//	SysTick_Config(SystemCoreClock/1000);
}


/**
* @brief	Configures the specified pin to behave either as an input or an output. 
* @param	pin		the number of the pin whose mode you wish to set
* @param	mode	INPUT or OUTPUT
* @retval	None
*/
void pinMode(uint8_t pin, int mode)
{
	GPIO_InitTypeDef gpio_init_struct;
	GPIO_TypeDef *gpio_port = digitalPinToPort(pin);
	uint16_t gpio_pin = digitalPinToBitMask(pin);

	// Disable PWM pin of timer
	switch(pin) {
		case 3:
			TIM_Cmd(TIM2, DISABLE);
			TIM_CtrlPWMOutputs(TIM2, DISABLE);     
			RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, DISABLE);   
			break;
		case 5:
			TIM_Cmd(TIM17, DISABLE);
			TIM_CtrlPWMOutputs(TIM17, DISABLE);     
			RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM17, DISABLE);   
			break;
		case 6:
			TIM_Cmd(TIM16, DISABLE);
			TIM_CtrlPWMOutputs(TIM16, DISABLE);     
			RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM16, DISABLE);   
			break;
		case 9:
			TIM_Cmd(TIM14, DISABLE);
			TIM_CtrlPWMOutputs(TIM14, DISABLE);     
			RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM14, DISABLE);   
			break;
		case 10:
			TIM_Cmd(TIM1, DISABLE);
			TIM_CtrlPWMOutputs(TIM1, DISABLE);     
			RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, DISABLE);   
			break;
		case 11:
			TIM_Cmd(TIM3, DISABLE);
			TIM_CtrlPWMOutputs(TIM3, DISABLE);     
			RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, DISABLE);   
			break;
		default:
			break;
	}
	
	if (mode == OUTPUT) {
		gpio_init_struct.GPIO_Mode = GPIO_Mode_OUT;
		gpio_init_struct.GPIO_OType = GPIO_OType_PP;
		gpio_init_struct.GPIO_Speed = GPIO_Speed_Level_3;
		gpio_init_struct.GPIO_PuPd = GPIO_PuPd_NOPULL;
		gpio_init_struct.GPIO_Pin = gpio_pin;
	} else {
		gpio_init_struct.GPIO_Mode = GPIO_Mode_IN;
		gpio_init_struct.GPIO_PuPd = GPIO_PuPd_UP;
		gpio_init_struct.GPIO_Pin = gpio_pin;		
	}
	GPIO_Init(gpio_port, &gpio_init_struct);
}


/**
* @brief	Reads the value from a specified digital pin, either HIGH or LOW.
* @param	pin		the number of the digital pin you want to read
* @retval	HIGH or LOW
*/
int digitalRead(uint8_t pin)
{
	GPIO_TypeDef *gpio_port = digitalPinToPort(pin);
	uint16_t gpio_pin = digitalPinToBitMask(pin);
	
	if (GPIO_ReadInputDataBit(gpio_port, gpio_pin) == Bit_SET) {
		return HIGH;
	}
	return LOW;
}


/**
* @brief	Write a HIGH or a LOW value to a digital pin.
* @param	pin		the pin number
* @param	value	HIGH or LOW
* @retval	None
*/
void digitalWrite(uint8_t pin, int value)
{
	GPIO_TypeDef *gpio_port = digitalPinToPort(pin);
	uint16_t gpio_pin = digitalPinToBitMask(pin);
	
	if (value == HIGH) {
		GPIO_WriteBit(gpio_port, gpio_pin, Bit_SET); 
	} else {
		GPIO_WriteBit(gpio_port, gpio_pin, Bit_RESET);
	}
}


/** 
* @brief	Reads the value from the specified analog pin.
* @param	pin		the number of the analog input pin to read from
* @retval	int (0 to 4095)
*/
int analogRead(uint8_t pin)
{
	ADC_ChannelConfig(ADC1, analogPinToChannel(pin), ADC_SampleTime_13_5Cycles);
	ADC_StartOfConversion(ADC1);
	while (ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) != SET);
	return ADC_GetConversionValue(ADC1);
}


/**
* @brief	Writes an analog value (PWM wave) to a pin.
* @param	pin		the pin to write to.
* @param	value	the duty cycle: between 0 (always off) and 255 (always on).
* @retval	None
*/
void analogWrite(uint8_t pin, uint16_t value)
{
	GPIO_InitTypeDef gpio_init_struct;
	TIM_TimeBaseInitTypeDef timebase_init_struct;
	TIM_OCInitTypeDef oc_init_struct;
	GPIO_TypeDef *gpio_port = digitalPinToPort(pin);
	uint16_t gpio_pin = digitalPinToBitMask(pin);
	uint16_t pwm_period;
	
	pinMode(pin, OUTPUT);
	if (value == 0) {
		digitalWrite(pin, LOW);
	}
	else if (value == 255) {
		digitalWrite(pin, HIGH);
	}
	else {
		// Configure GPIO port for output AF
		gpio_init_struct.GPIO_Mode = GPIO_Mode_AF;
    gpio_init_struct.GPIO_OType = GPIO_OType_PP;
		gpio_init_struct.GPIO_Speed = GPIO_Speed_Level_3;
		gpio_init_struct.GPIO_PuPd = GPIO_PuPd_NOPULL;
		gpio_init_struct.GPIO_Pin = gpio_pin;
		GPIO_Init(gpio_port, &gpio_init_struct);		
		
		// Configure timebase and output compare unit
		pwm_period = (SystemCoreClock / PWM_FREQ ) - 1; //Default frequency is 1KHz
		
		timebase_init_struct.TIM_Prescaler = 0;
		timebase_init_struct.TIM_CounterMode = TIM_CounterMode_Up;
		timebase_init_struct.TIM_Period = pwm_period;
		timebase_init_struct.TIM_ClockDivision = 0;
		timebase_init_struct.TIM_RepetitionCounter = 0;

		oc_init_struct.TIM_Pulse = (pwm_period)*value/255;
		pwmInputVal = (pwm_period)*value/255;
		
		//oc_init_struct.TIM_Pulse = (value+1)*16*16;
		pwmInputValMILI = (value+1)*16*16;
		oc_init_struct.TIM_OCMode = TIM_OCMode_PWM2;
		oc_init_struct.TIM_OutputState = TIM_OutputState_Enable;
		oc_init_struct.TIM_OutputNState = TIM_OutputNState_Enable;
		oc_init_struct.TIM_OCPolarity = TIM_OCPolarity_Low;
		oc_init_struct.TIM_OCNPolarity = TIM_OCNPolarity_High;
		oc_init_struct.TIM_OCIdleState = TIM_OCIdleState_Set;
		oc_init_struct.TIM_OCNIdleState = TIM_OCIdleState_Reset;

		switch(pin) {
			case 3:
				RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);  
				GPIO_PinAFConfig(GPIOB, GPIO_PinSource11, GPIO_AF_2);        
				TIM_TimeBaseInit(TIM2, &timebase_init_struct);
				TIM_OC4Init(TIM2, &oc_init_struct);
				TIM_OC4PreloadConfig(TIM2, TIM_OCPreload_Enable);
				TIM_SelectOnePulseMode(TIM2, TIM_OPMode_Repetitive); 
				TIM_Cmd(TIM2, ENABLE);
				TIM_CtrlPWMOutputs(TIM2, ENABLE);   
				break;
			case 5:
				RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM17, ENABLE);   
				GPIO_PinAFConfig(GPIOB, GPIO_PinSource9, GPIO_AF_2);     
				TIM_TimeBaseInit(TIM17, &timebase_init_struct);
				TIM_OC1Init(TIM17, &oc_init_struct);
				TIM_OC1PreloadConfig(TIM17, TIM_OCPreload_Enable);
				TIM_SelectOnePulseMode(TIM17, TIM_OPMode_Repetitive); 
				TIM_Cmd(TIM17, ENABLE);
				TIM_CtrlPWMOutputs(TIM17, ENABLE);  
				break;
			case 6:
				RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM16, ENABLE);   
				GPIO_PinAFConfig(GPIOB, GPIO_PinSource8, GPIO_AF_2);        
				TIM_TimeBaseInit(TIM16, &timebase_init_struct);
				TIM_OC1Init(TIM16, &oc_init_struct);
				TIM_OC1PreloadConfig(TIM16, TIM_OCPreload_Enable);
				TIM_SelectOnePulseMode(TIM16, TIM_OPMode_Repetitive); 
				TIM_Cmd(TIM16, ENABLE);
				TIM_CtrlPWMOutputs(TIM16, ENABLE);     
				break;
			case 9:
				RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM14, ENABLE);   
				GPIO_PinAFConfig(GPIOA, GPIO_PinSource4, GPIO_AF_4);        
				TIM_TimeBaseInit(TIM14, &timebase_init_struct);
				TIM_OC1Init(TIM14, &oc_init_struct);
				TIM_OC4PreloadConfig(TIM1, TIM_OCPreload_Enable);
				TIM_SelectOnePulseMode(TIM1, TIM_OPMode_Repetitive); 
				TIM_Cmd(TIM14, ENABLE);
				TIM_CtrlPWMOutputs(TIM14, ENABLE); 
				break;
			case 10:
				RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);   
				GPIO_PinAFConfig(GPIOA, GPIO_PinSource11, GPIO_AF_2);        
				TIM_TimeBaseInit(TIM1, &timebase_init_struct);
				TIM_OC4Init(TIM1, &oc_init_struct);
				TIM_OC4PreloadConfig(TIM1, TIM_OCPreload_Enable);
				TIM_SelectOnePulseMode(TIM1, TIM_OPMode_Repetitive); 
				TIM_Cmd(TIM1, ENABLE);
				TIM_CtrlPWMOutputs(TIM1, ENABLE);    
				break;
			case 11:
				RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);   
				GPIO_PinAFConfig(GPIOB, GPIO_PinSource5, GPIO_AF_1);        
				TIM_TimeBaseInit(TIM3, &timebase_init_struct);
				TIM_OC2Init(TIM3, &oc_init_struct);
				TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);
				TIM_SelectOnePulseMode(TIM3, TIM_OPMode_Repetitive); 
				TIM_Cmd(TIM3, ENABLE);
				TIM_CtrlPWMOutputs(TIM3, ENABLE);
				break;
			default:
				break;
		}
	}
}


/**
* @brief	Pauses the program for the amount of time (in miliseconds) specified as parameter. 
* @param	ms		the number of milliseconds to pause
* @retval	None
*/
//void delay(uint32_t ms)
//{
//	uint32_t start = msTick;
//	while ((msTick - start) < ms);
//}


/**
* @brief	Returns the number of milliseconds since the board began running the current program. 
* @param	None
* @retval	Number of milliseconds since the program started
* @remark	This number will overflow (go back to zero), after approximately 50 days.
*/
uint32_t millis(void)
{
	return msTick;
}
